// 1、无头单向非循环链表实现
public class SingleLinkedList {
    static class Node{
        public int val;
        public Node next;
        public Node(int val){
            this.val =val;
        }
    }
    Node head;
    //头插法
    public void addFirst(int data) {
        Node node = new Node(data);
        node.next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data) {
        Node node = new Node(data);
        //尾插法需要判断头节点是否为空，不然会空指针异常
        if (head == null) {
            head = node;
            return;
        }
        Node cur = head;
        //让头指针指向最后一个元素方便插入
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
    }

    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index, int data) {
        Node cur = head;
        //首位置就是头插法
        if (index <= 1) {
            addFirst(data);
            return;
        }
        //末位置就是尾插法
        if (index >= size()) {
            addLast(data);
            return;
        }
        //这里选用的是在哪一个位置
        while (index > 2) {
            cur = cur.next;
            index--;
        }
        Node node = new Node(data);
        node.next = cur.next;
        cur.next = node;
    }

    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        Node cur = head;
        while (cur != null) {
            if (cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    //删除第一次出现关键字为key的节点
    public void remove(int key) {
        if (head == null) {
            return;
        }
        Node cur = head;
        if (cur.val == key) {
            head = head.next;
            return;
        }
        while (cur.next != null) {
            if (cur.next.val == key) {
                cur.next = cur.next.next;
                return;
            }
            cur = cur.next;
        }
        System.out.println("数据不存在！");
    }
    //删除所有值为key的节点
    public void removeAllKey(int key){
        int len = size();
        if (head == null) {
            return;
        }
        Node cur = head.next;
        Node pre = head;
        while(cur != null) {
            if (cur.val == key) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        if (head.val == key) {
            head = head.next;
        }
        //当数据没有减少说明没有删除，也就是没有这个数据
        if(len == size()) {
            System.out.println("没有这个数据！");
        }
    }

    //得到单链表的长度
    public int size(){
        Node cur = head;
        int num = 0;
        while (cur != null) {
            cur = cur.next;
        }
        return num;
    }

    public void clear() {
        head = null;
    }
}


